<!-- 元数据编辑对话框 -->
<template>
  <CommonDialog v-model="visible" :loading="loading" :title="`${dataId ? '编辑' : '新建'}模型`" :width="400"
    @submit="submit" @cancel="cancel">
    <Form ref="formEl" :model="formData" :rules="rules" :label-width="100">
      <FormItem label="名称" prop="name">
        <Input v-model="formData.name" placeholder="请输入名称" />
      </FormItem>

      <FormItem label="上级分类">
        <el-tree-select v-model="formData.typeid" :data="departmentTree"
          :render-after-expand="false" teleported default-expand-all filterable
          placeholder="请选择上级分类" node-key="id"
          :props="{
            children: 'children',
            label: 'name'
          }"/>
      </FormItem>

      <FormItem label="类型">
        <Select v-model="formData.modeltype" transfer placeholder="请选择类型" filterable clearable>
          <Option v-for="item in MODELTYPE_OPTIONS" :value="item.value" :key="item.value">
            {{item.label}}
          </Option>
        </Select>
      </FormItem>

      <FormItem label="数据源">
        <Select v-model="formData.db" transfer placeholder="请选择数据源" filterable clearable>
          <Option v-for="item in dataSourceList" :value="item.id" :key="item.id">
            {{item.name}}
          </Option>
        </Select>
      </FormItem>
    </Form>
  </CommonDialog>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { Message } from 'view-ui-plus'

import { modelManage, dataSource } from '@/api/modules/modelSetting'

import { MODELTYPE_OPTIONS } from '@/util/conf'

import { listToTree } from '@/util/index'
import { ElTreeSelect } from 'element-plus'

const emit = defineEmits(['cancel', 'submit'])

const props = defineProps({
  currentTypeData: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)

const dataId = ref(undefined)
// 表单元素ref
const formEl = ref(null)
// 表单数据
const formData = ref({
  name: '', //名称
  db: '',
  typeid: props.currentTypeData.id,
  modeltype: ''
})

const departmentTree = ref([
  {
    name: '模型分类',
    id: '0',
    children: []
  }
])

// 表单校验条件
const rules = ref({
  name: [{ required: true, message: '请填写名称', trigger: 'blur' }]
})

const getTreeData = () => {
  return modelManage.typeList().then(({ data }) => {
    departmentTree.value[0].children = listToTree(data, {
      id: 'id',
      children: 'children',
      pid: 'parentid'
    })
  })
}

const dataSourceList = ref([])
const getSelectData = ()=> {
  return dataSource.page({
    query: {
      p: 1,
      ps: 9999
    }
  }).then(({data})=>{
    dataSourceList.value = data.content
  })
}

/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  try {
    const params = {
      ...formData.value,
      id: dataId.value
    }

    await modelManage[dataId.value ? 'edit' : 'add']({
      data: params
    })

    Message.success('操作成功')
    emit('submit')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  visible.value = false
  emit('cancel')
}

const getDetailData = () => {
  loading.value = true

  modelManage
    .detail({
      data: {
        id: dataId.value
      }
    })
    .then(({ data }) => {
      for (const key in formData.value) {
        formData.value[key] = data.cube[key]
      }
    }).finally(()=>{
      loading.value = false
    })
}

/**
 * 初始化对话框
 */
const initDialog = id => {
  // 显示对话框
  visible.value = true

  dataId.value = id

  if (id) {
    getDetailData()
  }
}

defineExpose({
  initDialog
})

onMounted(()=>{
  getTreeData()
  getSelectData()
})
</script>

<style scoped lang="scss">
.flex-form {
  display: flex;
}
.ivu-input-wrapper,
.ivu-select,
.el-select {
  width: 240px;
}
::deep(.ivu-form-item-label) {
  text-align: right;
}
</style>